﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Fayshine.VA.Helpers;
using Fayshine.VA.Models;
using Fayshine.VA.RIAService.Web;
using Fayshine.VA.ViewModels;
using Visifire.Charts;
using LocalBusyIndicator = Fayshine.VA.Controls.BusyIndicator;

namespace Fayshine.VA.Views.SearchStatistics.Week
{
    /// <summary>
    /// 周同期客流对比
    /// </summary>
    public partial class WeekSameDurationCompare : Page
    {
        private WeekReportViewModel m_ViewModel;

        public WeekSameDurationCompare()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(WeekSameDurationCompare_Loaded);
        }

        private void WeekSameDurationCompare_Loaded(object sender, RoutedEventArgs e)
        {
            LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
            indicator.IsBusy = true;

            startDatePicker.SelectedDate = DateTime.Now;

            m_ViewModel = new WeekReportViewModel();
            m_ViewModel.ResetHisotryChartEvent += new ResetHistoryChartEventHandler(m_ViewModel_ResetHisotryChartEvent);
            m_ViewModel.AppendHistoryPassengerFlow += new AppendHistoryPassengerFlowEventHandler(m_ViewModel_AppendHistoryPassengerFlow);
            this.DataContext = m_ViewModel;

            m_ViewModel.GetAllAreas();
        }

        void m_ViewModel_AppendHistoryPassengerFlow(string title, bool isIn, List<HistoryPassengerFlow> thisYearWeekPassneger, List<HistoryPassengerFlow> lastYearWeekPassenger)
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                DateTime time = startDatePicker.SelectedDate.Value;
                int weekNum = FayshineManager.Instance.GetWeekNumber(time);
                List<HistoryPassengerFlow> sourcePassengers = GetSourceHistoryPassengerFlow(isIn, thisYearWeekPassneger, lastYearWeekPassenger);

                // Chart title
                string title1 = "进";
                if (cmbInorOut.SelectedIndex == 1) title1 = "出";
                if (cmbInorOut.SelectedIndex == 2) title1 = "进出";

                string selectedAreas = m_ViewModel.CheckedAreas.Count == 1? 
                    string.Format("({0})", m_ViewModel.CheckedAreas[0].Name) : m_ViewModel.GetCheckedAreasText();
                Title vcChart1Title = new Visifire.Charts.Title();
                vcChart1Title.Text = string.Format("{0}年第{1}周同期{2}客流对比{3}",
                time.Year,
                weekNum,
                title1, selectedAreas);

                vcChart1.Titles.Add(vcChart1Title);
                //endof chart title

                vcChart1.DataPointWidth = 5;
                if (cmbInorOut.SelectedIndex == 0)
                {
                    DataSeries series = ChartHelper.GetDataSeries(RenderAs.Column, "", ChartValueTypes.Auto);
                    series.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
                    series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "InCount"));
                    series.DataSource = sourcePassengers;
                    vcChart1.Series.Add(series);
                }
                else if (cmbInorOut.SelectedIndex == 1)
                {
                    DataSeries series = ChartHelper.GetDataSeries(RenderAs.Column, "", ChartValueTypes.Auto);
                    series.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
                    series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "OutCount"));
                    series.DataSource = sourcePassengers;
                    vcChart1.Series.Add(series);
                }
                else if (cmbInorOut.SelectedIndex == 2)
                {
                    DataSeries series = ChartHelper.GetDataSeries(RenderAs.Column, "", ChartValueTypes.Auto);
                    series.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
                    series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "InCount"));
                    series.DataSource = sourcePassengers;
                    vcChart1.Series.Add(series);
                    DataSeries series2 = ChartHelper.GetDataSeries(RenderAs.Column, "", ChartValueTypes.Auto);
                    series2.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
                    series2.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "OutCount"));
                    series2.DataSource = sourcePassengers;
                    vcChart1.Series.Add(series2);
                }

                this.dataGrid.ItemsSource = sourcePassengers;

            });
        }

        private void m_ViewModel_ResetHisotryChartEvent()
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                if (vcChart1 != null)
                {
                    vcChart1.AxesX.Clear();
                    vcChart1.TrendLines.Clear();
                    vcChart1.Series.Clear();
                    vcChart1.Titles.Clear();
                }
            });
        }

        private void cmbAreas_DropDownClosed(object sender, EventArgs e)
        {
            if (m_ViewModel != null)
            {
                List<area> selectedArea = new List<area>();
                var selectAreaExt = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
                selectAreaExt.ForEach(b =>
                {
                    area temp = b.Tag as area;
                    selectedArea.Add(temp);
                });

                if (selectedArea.Count > 0)
                {
                    cbItemDisplay.Content = selectedArea.Count > 1 ? selectedArea[0].Name + "..." : selectedArea[0].Name;

                    if (selectedArea.Count > 1)
                    {
                        this.cmbPassenger.IsEnabled = false;
                    }
                    else
                    {
                        this.cmbPassenger.IsEnabled = true;
                    }

                }
                else
                {
                    cbItemDisplay.Content = string.Empty;
                }
                cmbAreas.SelectedItem = null;
                cmbAreas.SelectedItem = cbItemDisplay;

                m_ViewModel.SelectAreasChanged(selectedArea);
                cmbPassenger_DropDownClosed(null, null);
            }
        }

        private void cmbPassenger_DropDownClosed(object sender, EventArgs e)
        {
            if (m_ViewModel != null)
            {
                var selectMonitorAreaExts = m_ViewModel.MonitorAreaGateExts.Where(a => a.IsSelected).ToList();

                if (selectMonitorAreaExts.Count > 0)
                {
                    cbItemDisplay2.Content = selectMonitorAreaExts.Count > 1 ? selectMonitorAreaExts[0].Name + "..." : selectMonitorAreaExts[0].Name;

                }
                else
                {
                    cbItemDisplay2.Content = string.Empty;
                }
                cmbPassenger.SelectedItem = null;
                cmbPassenger.SelectedItem = cbItemDisplay2;
            }
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            string msg = string.Empty;
            m_ViewModel.UpdateCheckedAreas();

            if (!FayshineManager.Instance.ValidateAreaGateInputs(m_ViewModel.CheckedAreas,
                m_ViewModel.CheckedGates, ref msg))
            {
                MessageBox.Show(msg);
            }
            else
            {
                DateTime dateTime = startDatePicker.SelectedDate.Value;

                m_ViewModel.RefreshWeekCompareReport(true, new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0));
            }
        }

        private List<HistoryPassengerFlow> GetSourceHistoryPassengerFlow(bool isIn, List<HistoryPassengerFlow> thisYearWeekPassneger, List<HistoryPassengerFlow> lastYearWeekPassenger)
        {
            DateTime time = startDatePicker.SelectedDate.Value;
            int weekNum = FayshineManager.Instance.GetWeekNumber(time);
            List<HistoryPassengerFlow> sourcePassengers = new List<HistoryPassengerFlow>();

            HistoryPassengerFlow thisWeek = new HistoryPassengerFlow();
            thisWeek.DisplayTitle = "本周";
            thisWeek.AllInOut = thisYearWeekPassneger.Where(t => t.MonthOrDayOrWeek == weekNum).First().AllInOut;
            thisWeek.InCount = thisYearWeekPassneger.Where(t => t.MonthOrDayOrWeek == weekNum).First().InCount;
            thisWeek.OutCount = thisYearWeekPassneger.Where(t => t.MonthOrDayOrWeek == weekNum).First().OutCount;
            sourcePassengers.Add(thisWeek);

            HistoryPassengerFlow lastWeek = new HistoryPassengerFlow();
            lastWeek.DisplayTitle = "上周";
            lastWeek.AllInOut = thisYearWeekPassneger.Where(t => t.MonthOrDayOrWeek == weekNum - 1).First().AllInOut;
            lastWeek.InCount = thisYearWeekPassneger.Where(t => t.MonthOrDayOrWeek == weekNum - 1).First().InCount;
            lastWeek.OutCount = thisYearWeekPassneger.Where(t => t.MonthOrDayOrWeek == weekNum - 1).First().OutCount;
            sourcePassengers.Add(lastWeek);

            HistoryPassengerFlow lastYearWeek = new HistoryPassengerFlow();
            lastYearWeek.DisplayTitle = "去年同期";
            lastYearWeek.AllInOut = lastYearWeekPassenger.Where(t => t.MonthOrDayOrWeek == weekNum).First().AllInOut;
            lastYearWeek.InCount = lastYearWeekPassenger.Where(t => t.MonthOrDayOrWeek == weekNum).First().InCount;
            lastYearWeek.OutCount = lastYearWeekPassenger.Where(t => t.MonthOrDayOrWeek == weekNum).First().OutCount;
            sourcePassengers.Add(lastYearWeek);

            HistoryPassengerFlow thisYearAve = new HistoryPassengerFlow();
            thisYearAve.DisplayTitle = "今年平均";
            thisYearAve.AllInOut = Convert.ToInt32(thisYearWeekPassneger.Average(t => t.AllInOut));
            thisYearAve.InCount = Convert.ToInt32(thisYearWeekPassneger.Average(t => t.InCount));
            thisYearAve.OutCount = Convert.ToInt32(thisYearWeekPassneger.Average(t => t.OutCount));
            sourcePassengers.Add(thisYearAve);

            HistoryPassengerFlow lastYearAve = new HistoryPassengerFlow();
            lastYearAve.DisplayTitle = "去年平均";
            lastYearAve.AllInOut = Convert.ToInt32(lastYearWeekPassenger.Average(t => t.AllInOut));
            lastYearAve.InCount = Convert.ToInt32(lastYearWeekPassenger.Average(t => t.InCount));
            lastYearAve.OutCount = Convert.ToInt32(lastYearWeekPassenger.Average(t => t.OutCount));
            sourcePassengers.Add(lastYearAve);

            return sourcePassengers;
        }

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog fsd = new SaveFileDialog();
            fsd.Filter = "PDF (*.pdf)|*.pdf|*PNG (*.png)|*.png";

            if (fsd.ShowDialog() == true)
            {
                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = true;
                this.Dispatcher.BeginInvoke(delegate()
                {
                    FayshineManager.Instance.ExportToDisk(fsd, spContent);
                });
            }
        }
     
    }
}
